package com.snail.service.serviceImp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.mapper.BizProductReviewMapper;
import com.snail.model.pojo.mall.BizProductReview;
import com.snail.model.pojo.user.SysUser;
import com.snail.model.vo.mall.ProductReviewVO;
import com.snail.service.IBizProductReviewService;
import com.snail.service.SysUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class bizProductReviewServiceImpl extends ServiceImpl<BizProductReviewMapper, BizProductReview> implements IBizProductReviewService {
    @Resource
    private SysUserService sysUserService;

    @Override
    public List<ProductReviewVO> getReviewsByProductId(Integer productId) {
        // 1. 查询该商品的所有有效评论（包含一级和子评论）
        List<BizProductReview> allReviews = baseMapper.selectList(
                new LambdaQueryWrapper<BizProductReview>()
                        .eq(BizProductReview::getProductId, productId)
                        .eq(BizProductReview::getDeleted, 0)
                        .orderByDesc(BizProductReview::getCreateTime) // 按时间倒序
        );
        if (allReviews.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 转换为 VO 并关联用户信息
        List<ProductReviewVO> allReviewVOs = convertToVOs(allReviews);

        // 3. 构建评论树（嵌套子评论）
        return buildReviewTree(allReviewVOs);
    }

    // 转换为 VO 并填充用户信息
    private List<ProductReviewVO> convertToVOs(List<BizProductReview> reviews) {
        // 提取所有用户ID
        List<Long> userIds = reviews.stream()
                .map(BizProductReview::getUserId)
                .distinct()
                .collect(Collectors.toList());

        // 查询用户信息并构建 ID -> 用户的映射
        Map<Long, SysUser> userMap = sysUserService.listByIds(userIds).stream()
                .collect(Collectors.toMap(SysUser::getUserId, u -> u));

        // 转换为 VO
        return reviews.stream().map(review -> {
            ProductReviewVO vo = new ProductReviewVO();
            BeanUtils.copyProperties(review, vo);
            // 填充用户信息
            SysUser user = userMap.get(review.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
                vo.setFilePath(user.getFilePath());
            }
            return vo;
        }).collect(Collectors.toList());
    }

    // 构建嵌套评论树（核心逻辑）
    private List<ProductReviewVO> buildReviewTree(List<ProductReviewVO> allReviews) {
        // 1. 构建 ID -> 评论VO 的映射，方便查找父评论
        Map<Integer, ProductReviewVO> reviewMap = allReviews.stream()
                .collect(Collectors.toMap(ProductReviewVO::getId, vo -> vo));

        // 2. 分离一级评论（parentId=0）和子评论
        List<ProductReviewVO> rootReviews = new ArrayList<>();

        for (ProductReviewVO review : allReviews) {
            Integer parentId = review.getParentId();
            if (parentId == 0) { // 一级评论（无父评论）
                rootReviews.add(review);
            } else { // 子评论：找到父评论并添加到 children 中
                ProductReviewVO parentReview = reviewMap.get(parentId);
                if (parentReview != null) {
                    parentReview.getChildren().add(review);
                }
            }
        }

        return rootReviews;
    }

    @Override
    public boolean markDeletedById(Integer id) {
        LambdaUpdateWrapper<BizProductReview> wrapper = new LambdaUpdateWrapper<>();
        // WHERE条件：id = id（Lambda自动映射字段名）
        wrapper.eq(BizProductReview::getId, id);
        // 更新字段：deleted = 1（Lambda自动映射字段名）
        wrapper.set(BizProductReview::getDeleted, 1);

        int affectedRows = baseMapper.update(null, wrapper);
        return affectedRows > 0;
    }
}
